package com.woniuxy.interceptor;

import com.alibaba.fastjson.JSON;
import com.woniuxy.util.JWTUtil;
import com.woniuxy.util.ResponseData;
import com.woniuxy.util.ResponseEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

/**
 * @BelongsProject: pigTrotterStore
 * @BelongsPackage: com.woniuxy.interceptor
 * @Author: Quan
 * @Date: 2025/3/11 18:37
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {
	@Autowired
	private RedisTemplate<String, Object> redisTemplate;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		// 获取header中的token
		String token = request.getHeader("token");
		String jsonString = JSON.toJSONString(ResponseData.fail(ResponseEnum.NO_LOGIN));
		if (token == null) {
			response.getWriter().print(jsonString);
			return false;
		}
		// 对token进行认证
		if (!JWTUtil.verifyJWT(token)) {
			response.getWriter().print(jsonString);
			return false;
		}
		// 与redis数据库中的内容进行判断，是否相等
		Integer id = JWTUtil.getUserId(token);
		String redisToken = (String) redisTemplate.opsForValue().get("JWT:" + id);
		if (!token.equals(redisToken)) {
			response.getWriter().print(jsonString);
			return false;
		}
		// 对redis数据库中的数据有效期进行重新赋值
		redisTemplate.expire("JWT:" + id, 20, TimeUnit.DAYS);
		return true;
	}
}
